<?php

function myResponse($msg = '', $code = 1, $status = 200, $data = [], $total = null)
{
    // 允许来自如何域的请求（开发环境使用）
    header('Access-Control-Allow-Origin: *');

    // 生产环境使用
    // header('Access-Control-Allow-Origin: http://localhost:8081');

    // 允许的请求方法
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');

    // 允许的请求头
    header('Access-Control-Allow-Headers: Content-Type, Authorization');

    // 如果是预检请求(OPTIONS)，直接返回200
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        http_response_code(200);
        exit();
    }

    header('Content-Type: application/json');
    http_response_code($status);

    $data = [
        'msg' => $msg,
        'code' => $code,
        'data' => $data
    ];

    if ($total !== null) {
        $data['total'] = $total;
    }

    print_r(json_encode($data));
}